package com.tanhua.dubbo.api;

import cn.hutool.core.util.ObjectUtil;
import com.tanhua.model.mongo.RecommendUser;
import com.tanhua.model.mongo.Visitors;
import org.apache.dubbo.config.annotation.DubboService;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.List;

@DubboService
public class VisitorsApiImpl implements VisitorsApi{

    @Autowired
    private MongoTemplate mongoTemplate;

    @Override
    public void saveVisitor(Long userId, Long visitorUserId, String from) {
        Visitors visitors = new Visitors();
        try {
            // 校验 查询访客用户 今天是否已经记录过 如果已经记录过 不再记录
            Query query = Query.query(Criteria.where("userId").is(userId)
                    .and("visitorUserId").is(visitorUserId)
                    .and("visitDate").is(new DateTime().toString("yyyyMMdd")));
            boolean exists = mongoTemplate.exists(query,Visitors.class);
            if (exists){
                return ;
            }
            visitors.setUserId(userId);
            visitors.setVisitorUserId(visitorUserId);
            visitors.setFrom("首页");
            visitors.setDate(System.currentTimeMillis());
            visitors.setVisitDate(new DateTime().toString("yyyyMMdd"));
            mongoTemplate.save(visitors);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public List<Visitors> queryMyVisitor(Long userId,Long date) {
        // 查询 前5个访客数据 按照访问时间倒叙排序
        // 如果用户已经查询过列表 记录查询时间 后续查询需要按照这个时间往后查询
        // 上一次查询列表的时间
        /*Long date = Convert.toLong(redisTemplate.opsForHash().get(VISITOR_REDIS_KEY,String.valueOf(userId)));*/

        PageRequest pageRequest = PageRequest.of(0,5, Sort.by(Sort.Order.desc("date")));
        Query query = Query.query(Criteria.where("userId").is(userId))
                .with(pageRequest);
        if (ObjectUtil.isNotEmpty(date)){
            query.addCriteria(Criteria.where("date").gte(date));
        }
        List<Visitors> visitorsList = mongoTemplate.find(query, Visitors.class);

        //查询内阁来访 用户的得分
        for (Visitors visitors : visitorsList) {
            Query queryScore = Query.query(Criteria.where("toUserId")
                    .is(userId).and("userId").is(visitors.getVisitorUserId()));
            RecommendUser recommendUser = mongoTemplate.findOne(queryScore, RecommendUser.class);
            if (ObjectUtil.isNotEmpty(recommendUser)){
                visitors.setScore(recommendUser.getScore());
            }else {
                // 默认得分
                visitors.setScore(90d);
            }
        }
        return visitorsList;
    }























}
